import Vue from 'vue';
import App from './App.vue';
import router from "@/router/index";
import ElenentUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import "normalize.css";
import Cookie from "js-cookie";
import axios from "@/axios";
import store from "@/store";
import NProgress from "nprogress"
import "nprogress/nprogress.css"
import { Message } from "element-ui"
import * as echarts from "echarts";
import "animate.css"
import "../mock/mock"
import "@/filtter"

Vue.prototype.$http = axios;
Vue.config.productionTip = false;
Vue.use(ElenentUI);
Vue.prototype.$cookie = Cookie;
Vue.prototype.$charts = echarts;


// 刪除vuex中属性内容和cookie的内容
function removecoo() {
  Cookie.remove("login_tk")
  store.commit("removeCookie")
}

function verUser(cookieToken, next, to) {
  store.dispatch("verUserProfile", cookieToken).then(res => {
    if (res.code == -1) {
      Message.error("您的凭证错误，为了安全起见请重新登陆")
      removecoo()
      next("/login")
    } else {
      store.commit("addcookie", cookieToken)
      store.dispatch("promission/generatorRoutes", res.data.roles).then(res => {
        router.addRoutes(res)
        next(to)
      })
    }
  })
}

router.beforeEach((to, from, next) => {
  NProgress.start();
  let token = store.state.login_tk;
  let cookie_token = Cookie.get('login_tk');
  let userProfile = store.state.userProfile;
  let routes = store.state.promission.routes;
  if (to.path == "/login" && cookie_token) {
    store.dispatch("verUserProfile", cookie_token).then(res => {
      if (res.code == 0) {
        Message.error("请先退出登录")
        next(from.path)
      } else {
        Message.error("您的凭证错误，为了安全起见请重新登陆")
        removecoo()
        next("/login")
      }
    })
  }else {
    if (!token) {
      if (cookie_token) verUser(cookie_token, next, to)
      else {
        if (to.path == "/login") next()
        else next("/login")
      }
    } else {
      if (!userProfile) verUser(token, next, to)
      else {
        if (routes) next()
        else {
          store.dispatch("promission/generatorRoutes", userProfile.roles).then(res => {
            router.addRoutes(res)
            next(to)
          })
        }
      }
    }
  }
})


router.afterEach(() => {
  NProgress.done();
})



new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app')
